<template>
  <el-dialog
    v-model="visible"
    title="提交误报申请"
    width="700px"
    destroy-on-close
    @close="handleClose"
  >
    <div v-loading="loading" class="submit-container">
      <el-form
        ref="submitFormRef"
        :model="submitForm"
        :rules="rules"
        label-width="120px"
        size="default"
      >
        <el-form-item label="资产IP" prop="asset_ip">
          <el-input
            v-model="submitForm.asset_ip"
            placeholder="请输入资产IP地址"
            clearable
          />
        </el-form-item>

        <el-form-item label="维度代码" prop="dimension_code">
          <el-select
            v-model="submitForm.dimension_code"
            placeholder="请选择维度代码"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="dim in dimensionList"
              :key="dim.value"
              :label="`${dim.label} (${dim.value})`"
              :value="dim.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="误报原因" prop="false_positive_reason">
          <el-input
            v-model="submitForm.false_positive_reason"
            type="textarea"
            :rows="4"
            placeholder="请输入误报原因说明"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="证据材料" prop="evidence">
          <el-input
            v-model="submitForm.evidence"
            type="textarea"
            :rows="3"
            placeholder="请输入证据材料（日志、截图链接等）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="处理方式" prop="handling_method">
          <el-radio-group v-model="submitForm.handling_method">
            <el-radio label="exclude_from_score">从评分中排除</el-radio>
            <el-radio label="adjust_score">调整分数</el-radio>
            <el-radio label="mark_only">仅标记</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="submitForm.handling_method === 'adjust_score'"
          label="分数调整值"
          prop="score_adjustment"
        >
          <el-input-number
            v-model="submitForm.score_adjustment"
            :min="-100"
            :max="100"
            :precision="2"
            placeholder="请输入分数调整值"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        提交申请
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessage, ElForm } from "element-plus";
import { submitFalsePositive } from "../../../servers";
import { getDimensionList } from "../../../servers";
import { useUserStoreHook } from "@/store/modules/user";

// 定义属性和事件
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["refresh-list", "update:modelValue"]);

// 响应式数据
const visible = ref(props.modelValue);
const loading = ref(false);
const submitFormRef = ref<InstanceType<typeof ElForm>>();

// 维度列表
const dimensionList = ref<Array<{ label: string; value: string }>>([]);

// 表单数据
const submitForm = reactive({
  asset_ip: "",
  dimension_code: "",
  false_positive_reason: "",
  evidence: "",
  handling_method: "exclude_from_score" as
    | "exclude_from_score"
    | "adjust_score"
    | "mark_only",
  score_adjustment: 0,
});

// 表单验证规则
const rules = {
  asset_ip: [{ required: true, message: "请输入资产IP地址", trigger: "blur" }],
  dimension_code: [
    { required: true, message: "请选择维度代码", trigger: "change" },
  ],
  false_positive_reason: [
    { required: true, message: "请输入误报原因", trigger: "blur" },
    { min: 10, message: "误报原因至少10个字符", trigger: "blur" },
  ],
  score_adjustment: [
    {
      required: true,
      message: "请输入分数调整值",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (submitForm.handling_method === "adjust_score") {
          if (value === null || value === undefined || value === "") {
            callback(new Error("请输入分数调整值"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
    },
  ],
};

// 获取维度列表
const fetchDimensionList = async () => {
  try {
    const response = await getDimensionList({ page_size: 100 });
    const data = response.data?.data || response.data;
    const dimensions = data?.dimensions || data?.items || [];
    dimensionList.value = dimensions.map((d: any) => ({
      label: d.dimension_name || d.dimension_code,
      value: d.dimension_code,
    }));
  } catch (error) {
    console.error("获取维度列表失败:", error);
  }
};

// 监听显示状态变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
    if (!val) {
      resetForm();
    }
  }
);

// 重置表单
const resetForm = () => {
  submitForm.asset_ip = "";
  submitForm.dimension_code = "";
  submitForm.false_positive_reason = "";
  submitForm.evidence = "";
  submitForm.handling_method = "exclude_from_score";
  submitForm.score_adjustment = 0;
  if (submitFormRef.value) {
    submitFormRef.value.resetFields();
  }
};

// 提交申请
const handleSubmit = async () => {
  if (!submitFormRef.value) return;

  try {
    await submitFormRef.value.validate();

    loading.value = true;

    const submitData: any = {
      asset_ip: submitForm.asset_ip,
      dimension_code: submitForm.dimension_code,
      false_positive_reason: submitForm.false_positive_reason,
      handling_method: submitForm.handling_method,
      marked_by: useUserStoreHook()?.username || "system",
    };

    if (submitForm.evidence) {
      submitData.evidence = submitForm.evidence;
    }

    if (
      submitForm.handling_method === "adjust_score" &&
      submitForm.score_adjustment !== undefined
    ) {
      submitData.score_adjustment = submitForm.score_adjustment;
    }

    await submitFalsePositive(submitData);

    ElMessage.success("误报申请提交成功");
    emit("refresh-list");
    handleClose();
  } catch (error: any) {
    if (error.name !== "ValidationError") {
      ElMessage.error(error.message || "提交失败，请重试");
    }
  } finally {
    loading.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  emit("update:modelValue", false);
};

// 初始化
onMounted(() => {
  fetchDimensionList();
});
</script>

<style scoped lang="scss">
.submit-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}
</style>
